<?php

/*
 * 调用插件资源的Action
 *
 */

class callAction extends Action
{
    /*
     * 调用指定插件的指定方法
     * $params为json对象
     * $isLogBrowser  1 为访问页面日志预览  不记录到用户浏览记录
     */
    public function index($module = '', $method = '', $params = NULL, $menuOnlymember = 0, $AccessTags = 0, $isLogBrowser = 0, $by = null, $openid = null,$token = null)
    {
        if ($_GET['from'] == 10) {
            header("Location:http://wxtest.mboxone.com/test/call.html?userName=&customerId=3&module=mall&method=getMall&params=%7B%22id%22:544%7D");
        }
        $retVal = Session::init();
        $customerId = Session::$user['customerId'];
        $userName = Session::$user['userName'];
        $this->checkCustomer($customerId);
        Session::switchCustomer(0);
        $customer_user = M('customer_user');
        $miMallUserModel = M('mimall_user');
        Session::switchCustomer($customerId);
//        $miUser = $miMallUserModel->where("(cId=$customerId or cId is NULL) and openid='" . $userName . "'")->find();
        if (isset($params)) {
            $obj = Output::instance()->toObject($params);
            $obj->fromModule = $module;
            $obj->fromMethod = $method;
//            empty($miUser) ? $obj->statis = 1 : '';
        }
        //$by = $_GET['by'];
        //$openid = $_GET['openid'];
        if(isset($obj->isDefault)){
            $obj = self::scanVisit($obj);
        }
        if ($by == NULL) {
            //区分浏览器
            if(!isMicroMessengerUserAgent()){
                if (!isset($params)) {
                    $obj = Output::instance()->toObject($params);
                }
                if($token){
                    $obj->token = $token;
                    cookie("token", $token, array('expire' => 3600 * 24 * 365, 'path' => '/'));
                }else{
                    $obj->token = $_COOKIE['token'];
                }
                $tokenString = base64_decode($obj->token);
                Session::$user['userId']  = substr($tokenString,14);
//                $this->oauthToken($token,$params,$obj);
            }else{
                //添加
                $this->oauth($module, $method);
                $this->setUserMimall($obj);
            }
        } else if ($by == 'noOauth'){
            //添加
            $this->oauthPhone($by);
            $this->setUserMimall($obj);
            //不需要授权，此处不做处理
            // $userName = cookie("openid_$customerId");
            // if(empty($userName)){
            //     $return['code'] = 1;
            //     $return['msg'] = "未授权，请授权后进入";
            //     Output::instance()->object($return);
            //     return;
            // }
        }
          else if($by == 'token'){
              if (!isset($params)) {
                  $obj = Output::instance()->toObject($params);
              }
               if($token){
                   $obj->token = $token;
               }else{
                   $obj->token = $_COOKIE['token'];
               }
               $tokenString = base64_decode($obj->token);
               Session::$user['userId']  = substr($tokenString,14);
//              $this->oauthToken($token,$params,$obj);
        }
        else {
            if ($openid) {
                Session::switchCustomer($customerId);
                $User = M('user');
                $userinfo = $User->where(['wxAppOpenid'=>$openid])->find();
                Session::$user['userId']=$userinfo['id'];
                Session::$user['userName']=$userinfo['userName'];
            }else{
                $this->oauthapp($module,$method,$obj);
            }
            //小程序入口
        }
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        // Session::$user['userId']=23;
        // Session::$user['uid']=613;
        // $accessTag = $this->handleTag($AccessTags);

        // if (!$accessTag) {
        //  return;
        // }
        Module::callModule($module, Session::$user, $method, $obj);
    }

    //设置session
    public function oauthToken($token,$params,$obj){
        if (!isset($params)) {
            $obj = Output::instance()->toObject($params);
        }
        if($token){
            $obj->token = $token;
        }else{
            $obj->token = $_COOKIE['token'];
        }
        $tokenString = base64_decode($obj->token);
        Session::$user['userId']  = substr($tokenString,14);
    }

    public function oauthapp($module, $method, $obj, $mediaId = 0)
    {
        $customerId = Session::$user['customerId'];
        $User = M('user');
        $UserWeixinInfo = M('user_weixin_info');
        Session::switchCustomer(0);
        $IndMediaInfo_Model = M('ind_media_info');
        $customer_user = M('customer_user');
        /***** LLyeap_delete *****/
//        $Customer = M('customer');
        /*****  *****/

        Session::switchCustomer($customerId);
        /**
         * 这里的customer主要用户获取小程序相关内容
         * 筛选条件来自Session(id)
         * 后面可以将mediaId也加到Session里
         * ** 这里修改到wx_X_user和wx_X_user_weixin_info
         * LLyeap_wx_customer修改
         */
        if ($mediaId > 0) { // 如果拿到了$mediaId, 则通过id来筛选
            $where_info = ['cid' => $customerId, 'id' => $mediaId];
        } else {        // 如果没有$mediaId, 则拿这个cid下默认的账号, 即default = 1的, 只有一个
            $where_info = ['cid' => $customerId, 'isDefault' => 1];
        }
        $customer = $IndMediaInfo_Model->where($where_info)->find();
        /***** LLyeap_delete *****/
//        $customer = $Customer->where(['id'=>$customerId])->find();
        /*****  *****/

        if ($module == 'indexApp' && $method == 'index') {
            //通过code获取session_key
            $sessionKey = self::httpGet($obj->code, $customer['wxAppAppid'], $customer['wxAppSecret']);
            if (!$sessionKey['errcode']) {
                $iv = $obj->iv;
                $encryptedData = str_replace('\\', '', $obj->encryptedData);
                $session_key = $sessionKey['session_key'];
                include_once APP_PATH . 'Lib/wxapp/wxBizDataCrypt.php';
                $pc = new WXBizDataCrypt($customer['wxAppAppid'], $session_key);
                $errCode = $pc->decryptData($encryptedData, $iv, $data);
                if ($errCode != 0) {
                    Output::instance()->resultCode(code_access_denied);
                    return;
                }

                $json = json_decode($data);
                $datauser['role'] = 'User';
                $datauser['subscribeTime'] = date('Y-m-d H:i:s', time());
                $datauser['wxAppOpenid'] = $sessionKey['openid'];
                $datauser['session_key'] = $sessionKey['session_key'];
                $datauser['expires_in'] = $sessionKey['expires_in'];
                $obj->unionId ? $where['unionid'] = $obj->unionId : $where['openid'] = $sessionKey['openid'];
                $findUserId = $UserWeixinInfo->where($where)->getField("userId");
                if (!$findUserId) {
                    $findUserId = $User->where("wxAppOpenid='" . $sessionKey['openid'] . "'")->getField("id");
                }
                if ($findUserId) { //
                    Session::$user['appopenid'] = $sessionKey['openid'];
                    Session::$user['userId'] = $findUserId;
                    $updatuser = $User->where(['id' => $findUserId])->save($datauser);
                    if ($updatuser) {
                        self::addUserInfoToDbApp($json, $findUserId);
                    }
                } else {
                    Session::$user['appopenid'] = $sessionKey['openid'];
                    $datauser['userName'] = $sessionKey['openid'];
                    $updatuser = $User->add($datauser);
                    if ($updatuser) {
                        self::addUserInfoToDbApp($json, $updatuser);
                        Session::$user['userId'] = $updatuser;
                    }
                }

            } else {
                Output::instance()->object($sessionKey);
                return;
            }
        } else {
            Session::$user['userId'] = $_COOKIE["appuserid_" . $customerId];
        }
    }
    //设置mimalluser
    public function setUserMimall($params, $mediaId = 0)
    {
        $uid = Session::$user['userId'];
        $userName = Session::$user['userName'];
        $customerId = Session::$user['customerId'];
        if (isMicroMessengerUserAgent()) {
            if (!$userName) {
                return;
            }
            Session::switchCustomer(0);
            $miMallUserModel = M("mimall_user");
            /**
             * 这里customer是用于查询公众号自动分组的开启情况
             * 筛选条件(id)来自Session
             * media也需要加到Session里
             * LLyeap_wx_customer修改
             */
            $IndMediaInfo_Model = M('ind_media_info');
            /***** LLyeap_delete *****/
//            $customerModel = M('customer');
            /*****  *****/

            $quanModel = M("miyouquan");
            $quanuser = M("quan_user");
            Session::switchCustomer($customerId);
            $miUser = $miMallUserModel->where("(cId=$customerId or cId is NULL) and openid='" . $userName . "'")->find();
            if (!$uid) {
                $uid = cookie("userId_$customerId");
                if (!$uid) {
                    $uid = $miUser['uId'];
                    cookie("userId_$customerId", $uid, array('expire' => 3600 * 24 * 365, 'path' => '/'));
                }
                Session::$user['userId'] = $uid;
            }

            if (!$miUser || count($miUser) < 1) {
                $miUid = $params->miUId;
                $qId = $params->qId;
                $module = $params->fromModule;
                $method = $params->fromMethod;
                $recommenderId = $params->recommenderId;
                if ($miUid && $qId && $uid) {
                    switch ($module) {
                        case "tuan":
                            $id = $params->teamId;
                            break;
                        case 'product':
                            if ($method == 'getProduct') {
                                $id = $params->id;
                            } else if ($method == 'getProductByTagId') {
                                $id = $params->tagId;
                                $module = 'getProductByTagId';
                            }
                            break;
                        default:
                            $id = $params->id;
                            break;
                    }
                    //取出对应的销售源以及推荐人的相关信息
                    $quanUserInfo = $quanuser->field("refereeUid,saleSource")->where("qid=$qId and uid=$miUid and deleted=0")->find();
                    //取出三级推荐人
                    if (!empty($quanUserInfo['refereeUid'])){
                        $prePreRefereeInfo = $quanuser->where("qid=$qId and uid=".$quanUserInfo['refereeUid'].' and deleted=0')->getField("refereeUid");
                    }else {
                        $prePreRefereeInfo = '';
                    }
                    $addData = array(
                        "openid" => $userName,
                        "qId" => $qId,
                        "miUid" => $miUid,
                        "uId" => $uid,
                        "createTime" => date('Y-m-d H:i:s'),
                        "cId" => $customerId,
                        "fromModule" => $module,
                        "fromModuleId" => $id,
                        "saleSource"=>$quanUserInfo['saleSource'],
                        "refereeUid"=>$quanUserInfo['refereeUid'],
                        "preRefereeUid"=>$prePreRefereeInfo,
                        "prePreRefereeUid"=> '',
                        "recommenderId"=> $recommenderId,
                    );
//                    $success = StatisTicsAction::miMallUserSave('', $addData, $customerId);
                    $success = $miMallUserModel->add($addData);
                    if ($success) {
                        $this->newUserPoint($addData, 0);
                        $sendParmas = new stdClass();
                        $sendParmas->qid = $qId;
                        $sendParmas->uid = $miUid;
                        $sendParmas->userName = $userName;
                        $sendParmas->cid = $customerId;
                        Module::callModule("community", NULL, "newFansMessage", $sendParmas);
                    }
                }
            } else if (!$miUser["uId"] && $uid) {
                $miMallUserModel->where("id=" . $miUser["id"])->setfield("uId", $uid);
            }
            //自动分组
            if ($mediaId > 0) { // 如果拿到了$mediaId, 则通过id来筛选
                $where_info = ['cid' => $customerId, 'id' => $mediaId];
            } else {        // 如果没有$mediaId, 则拿这个cid下默认的账号, 即default = 1的, 只有一个
                $where_info = ['cid' => $customerId, 'isDefault' => 1];
            }
            $customerUserInfo = $IndMediaInfo_Model->where($where_info)->find();
            /***** LLyeap_delete *****/
//            $customerUserInfo = $customerModel->where('id='.$customerId)->find();
            /*****  *****/

            if ($customerUserInfo['isAutoGroup']) {
                if (!$params->qId) {
                    return;
                }
                $quanInfo = $quanModel->where("id=" . $params->qId)->find();
                $usergroup = D("user_weixin_group");
                $condition['group_name'] = array('eq', $quanInfo['name']);
                $groupResult = $usergroup->where($condition)->find();
                if (!$groupResult) {
                    $groupResult = WeixinApi::createUserTag($quanInfo['name']);
                    $groupResult = json_decode($groupResult, true);
                    if ($groupResult['errcode']) {
                        Log::write("创建分组失败   " . $groupResult['errmsg']);
                    } else {
                        $groupId = $groupResult['tag']['id'];
                        $groupdata['group_id'] = $groupResult['tag']['id'];
                        $groupdata['group_name'] = $groupResult['tag']['name'];
                        $groupdata['count'] = 0;
                        $usergroup->add($groupdata);
                    }
                } else {
                    $groupId = $groupResult['group_id'];
                }
                $userModel = D("user");
                $groupIds = $userModel->where("userName='" . $userName . "'")->getField("groupId");
                $groupIds = explode(",", $groupIds);
                if ($groupId && !in_array($groupId, $groupIds)) {
                    if (count($groupIds) >= 3) {
                        WeixinApi::deletedUsersTag(explode(',', $userName), $groupIds[0]);
                        array_shift($groupIds);
                    }
                    array_push($groupIds, $groupId);
                    WeixinApi::setUsersTag(explode(',', $userName), $groupId);
                    $userModel->where("userName='$userName'")->setField("groupId", implode(",", $groupIds));
                }
            }
        }
    }

    /**给予邀请积分
     * @param $data
     */
    public static function newUserPoint($data, $new = 1)
    {
        $InviteRewardModel = D('InviteReward', 'Logic');
        $pointModel = D('Point', 'Logic');
        $userModel = M('user');
        $points = $InviteRewardModel->getInvitePoint();
        foreach ($points as $point) {
            $pointConfig = [
                'userId' => $data['uId'],
                'miUid' => $data['miUid'],
                'refereeUid' => $data['refereeUid'],
                'preRefereeUid' => $data['preRefereeUid'],
                'recommenderId' => $data['recommenderId'],
                'newUserPoint' => $point['newUserPoint'],
                'newMiPoint' => $point['newMiPoint'],
                'newPreMiPoint' => $point['newPreMiPoint'],
                'newPrePreMiPoint' => $point['newPrePreMiPoint'],
                'newRecommenderPoint' => $point['newRecommenderPoint'],
            ];
            if (!$point['noInviteNewReward'] && !$pointConfig['recommenderId']) $pointConfig['newUserPoint'] = 0;//非邀请情况不得积分
//            $isSubscribe = 0;
//            if ($InviteRewardModel->ifSubscribe($data['uId'])) {
//                $pointConfig['subscribeUserPoint'] = $point['subscribeUserPoint'];
//                $pointConfig['subscribeMiPoint'] = $point['subscribeMiPoint'];
//                $pointConfig['subscribePreMiPoint'] = $point['subscribePreMiPoint'];
//                $pointConfig['subscribePrePreMiPoint'] = $point['subscribePrePreMiPoint'];
//                $pointConfig['subscribeRecommenderPoint'] = $point['subscribeRecommenderPoint'];
//                $isSubscribe = 1;
//            }
            /*添加邀请记录*/
            $record = $InviteRewardModel->getInviteRecord(['userId' => $data['uId'], 'type' => 0], 'find');
            $id = $record['id'];
            $recordId = $InviteRewardModel->addInviteRecord(
                $data['uId'],
                $point['inviteRewardId'],
                $data['recommenderId'],
                0,
                $point['newUserPoint'],
                0,
                null,
                0,
                null,
                json_encode($pointConfig),
                $id
            );

            $isNew = $userModel->where(['id' => $data['uId']])->getField('isNew');
            /*加邀请新用户积分*/
            if (!empty($pointConfig['newUserPoint']) && $new == 1) { //给新用户加积分
                $pointModel->addPoint(
                    $pointConfig['userId'],
                    $pointConfig['newUserPoint'],
                    'invite',
                    $recordId,
                    '成为新用户',
                    '',
                    $point['pointSchemeId'],
                    $point['pointSchemeName']
                );
            }

            if ($isNew == 1 && $new == 0) {
                if (!empty($pointConfig['newMiPoint']) && $pointConfig['miUid']) { //给注册好友积分
                    $pointModel->addPoint(
                        $pointConfig['miUid'],
                        $pointConfig['newMiPoint'],
                        'invite',
                        $recordId,
                        '邀请好友成为新用户',
                        '',
                        $point['pointSchemeId'],
                        $point['pointSchemeName']
                    );
                }

                if (!empty($pointConfig['newPreMiPoint']) && $pointConfig['refereeUid']) { //给注册好友推荐人积分
                    $pointModel->addPoint(
                        $pointConfig['refereeUid'],
                        $pointConfig['newPreMiPoint'],
                        'invite',
                        $recordId,
                        '好友邀请新用户',
                        '',
                        $point['pointSchemeId'],
                        $point['pointSchemeName']
                    );
                }

                if (!empty($pointConfig['newPrePreMiPoint']) && $pointConfig['preRefereeUid']) { //给注册好友上级推荐人积分
                    $pointModel->addPoint(
                        $pointConfig['preRefereeUid'],
                        $pointConfig['newPrePreMiPoint'],
                        'invite',
                        $recordId,
                        '好友邀请新用户',
                        '',
                        $point['pointSchemeId'],
                        $point['pointSchemeName']
                    );
                }

                if (!empty($pointConfig['newRecommenderPoint']) && $pointConfig['recommenderId']) { //给推荐好友积分
                    $pointModel->addPoint(
                        $pointConfig['recommenderId'],
                        $pointConfig['newRecommenderPoint'],
                        'invite',
                        $recordId,
                        '邀请好友成为新用户',
                        '',
                        $point['pointSchemeId'],
                        $point['pointSchemeName']
                    );
                }
                $userModel->where(['id' => $data['uId']])->setField('isNew', 0);
            }
        }
    }


    /*
     * 提供一个链接用来直接调用插件里的html页面
     * $module 模块名
     * $template 模版名，如果要显示add.html，则输入add即可
     * $params json的参数，将会原样输出到模版中
     */
    public function page($module, $template, $params = NULL, $menuOnlymember = 0, $AccessTags = 0)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $this->oauth($module);
        $customerUser = $this->verifyCustomer(Session::$user['customerId']);
        if (!isset($customerUser)) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $retMemeber = $this->handleMemeber($menuOnlymember);
        if (!$retMemeber) {
            return;
        }
        $accessTag = $this->handleTag($AccessTags);

        if (!$accessTag) {
            return;
        }
        if (isset($params)) {
            $obj = Output::instance()->toObject($params);
        }

        Output::instance()->module($module, $template)->object($obj);
    }

    private function handleTag($accesstagids)
    {
        if ($accesstagids) {

            $userName = Session::$user['userName'];
            if ($userName == '') {
                Output::instance()->resultCode(code_user_not_member);
                return false;
            } else {
                $Access = $this->verifyAccessTags($accesstagids);
                switch ($Access) {
                    case 0:
                        $tagName = M("access_tag");
                        $mctag["accesstagid"] = array('in', $accesstagids);
                        $tagNamesarr = $tagName->where($mctag)->select();
                        $tagNamesarrs = '';
                        foreach ($tagNamesarr as $value) {
                            $tagNamesarrs .= $value['tagName'] . ',';
                        }
                        $tagNamesarrs = substr($tagNamesarrs, 0, strlen($tagNamesarrs) - 1);
                        $tagNamesarrs = '仅' . $tagNamesarrs . '可见';
                        $obj = array('code' => code_member_not_access, 'msg' => $tagNamesarrs);
                        Output::instance()->tpl('error.html')->object($obj);
                        return false;
                    case 1://审核通过
                        return true;
                    default:
                        Output::instance()->resultCode(code_user_not_member);
                        return false;
                }
//              if(!$isMember){
//                  Output::instance()->resultCode(code_user_not_member);
//                  return;
//              }
            }
        }
        return true;
    }

    private function handleMemeber($menuOnlymember)
    {
        if ($menuOnlymember) {
            $userName = Session::$user['userName'];
            if ($userName == '') {
                Output::instance()->resultCode(code_user_not_member);
                return false;
            } else {
                $isMember = R("Member/verifyMember");
                switch ($isMember) {
                    case -1:
                        Output::instance()->resultCode(code_user_not_member);
                        return false;
                    case 0:
                        Output::instance()->resultCode(code_user_member_not_check);
                        return false;
                    case 1://审核通过
                        return true;
                    case 2:
                        Output::instance()->resultCode(code_user_member_is_checking);
                        return false;
                    default:
                        Output::instance()->resultCode(code_user_not_member);
                        return false;
                }
//              if(!$isMember){
//                  Output::instance()->resultCode(code_user_not_member);
//                  return;
//              }
            }
        }
        return true;
    }

    private function isAddUserInfo($userName)
    {
        $UserWeixinInfoModel = M('user_weixin_info');
        $whereUserInfo['openid'] = $userName;
        $whereUserInfo['nickname'] = array('exp', 'IS NOT NULL');
        $userInfo = $UserWeixinInfoModel->where($whereUserInfo)->find();
        Log::write($UserWeixinInfoModel->getlastsql());
        if ($userInfo && count($userInfo) > 0) {
            return true;
        } else {
            return false;
        }
    }

    private function setOauthCookie($userName, $UnionID = null)
    {
        $customerId = Session::$user['customerId'];
        if (isset($userName)) {
            cookie("openid_$customerId", $userName, array('expire' => 3600 * 24 * 60, 'path' => '/'));
            //cookie("openid_$customerId",$userName,array('expire'=>30,'path'=>'/'));
        }
        if (!empty($UnionID)) {
            cookie("unionID_$customerId", $UnionID, array('expire' => 3600 * 24 * 60, 'path' => '/'));
        }
    }

    private function oauth($module, $method)
    {
        $customerId = Session::$user['customerId'];
        $force = $_GET["force"]; //订单页面需要强制授权
        //微信浏览器授权
        $userName = cookie("openid_$customerId");
        if (isMicroMessengerUserAgent()) {
            $clear = $_GET["clear"];
            if ($clear || strpos($userName, "gid_") !== false) {
                cookie("openid_$customerId", null);
                cookie("unionID_$customerId", null);
                cookie("userId_$customerId", null);
                $userName = '';
            }
            $UnionID = cookie("unionID_$customerId");
            $scope = $_GET["scope"];
            if ($scope) {
                if(!empty($userName)){
                    $userModel = D("user");
                    $userWhere['userName']=array('eq',$userName);
                    $newTime = date("Y-m-d H:i:s");
                    $userWhere['subscribeTime'] =array('gt',date('Y-m-d H:i:s',strtotime("$newTime - $scope day")));
                    $result = $userModel->where($userWhere)->find();
                    $result?$force=0:$force=1;
                }
                $scope = SNSAPI_USERINFO;
            } else {
                $scope = SNSAPI_BASE;
            }
//          if(empty($userName)){
//              $userName=$_GET["userName"];
//              Log::write('地址栏userName is '. $userName);
//          }
            if ($force || empty($userName)) { //  需要强制授权或者cookie中userName为空
                $access = WeixinApi::getOauthAccessToken($scope);//授权
                if ($access) {
                    Session::$user['userName'] = $access->openid;
                    Session::$user['unionID'] = $access->unionid;
                    $userName = Session::$user['userName'];
                    $UnionID = Session::$user['unionID'];
                    $this->setOauthCookie($userName, $UnionID);
                    if ($access) { //高级授权获取用户信息入库
                        if ($scope == SNSAPI_USERINFO) {
                            $userInfo = WeixinApi::getOauthUserInfo($access);
                            if ($userInfo) {
                                $userId = $this->setUserOauthToken($userName, $access->access_token, $access->expiration, $access->refresh_token, $UnionID);
                                $this->addUserInfoToDb($userName, $UnionID, $userInfo, $userId);

                            }
                        } else { //普通授权
                            $userInfo = WeixinApi::getUserInfo($userName);
                            if ($userInfo) {
                                $userId = $this->setUserOauthToken($userName, $access->access_token, $access->expiration, $access->refresh_token, $UnionID, USER_STATUS_SUBSCRIBE, $userInfo->subscribe_time, $userInfo->tagid_list);
                                $this->addUserInfoToDb($userName, $userInfo->unionid, $userInfo, $userId);
                            } else {
                                $userId = $this->setUserOauthToken($userName, $access->access_token, $access->expiration, $access->refresh_token, $UnionID);
                                $this->addUserInfoToDb($userName, $UnionID, "", $userId);
                            }
                        }
                    }
                } else {
                    Log::write('授权出错');
                    Session::$user['userName'] = "";
                    Session::$user['unionID'] = "";
                    return;
                }
            }
            if (!Session::$user["userId"]) {
                $userId = cookie("userId_$customerId");
                if (!$userId) {
                    $userModel = D("user");
                    $userId = $userModel->where("openid='$userName'")->getField("id");
                    Session::$user["userId"] = $userId;
                } else {
                    Session::$user["userId"] = $userId;
                }
            }
            if (!empty($userName)) {
                Session::$user["userName"] = $userName;
            }
            if (!empty($UnionID)) {
                Session::$user["unionID"] = $UnionID;
            }
            $userName = Session::$user["userName"];
            $UnionID = Session::$user["unionID"];
            if (empty($userName)) {
                Output::instance()->resultCode(code_access_denied);
                return;
            }
        } else {
            if (!$userName) {
                $Guid = new Guid();
                $userName = $Guid->toString();//生成临时userName;
                $userName = "gid_" . str_replace('-', "", substr($userName, 0, 28));
                cookie("openid_$customerId", $userName, array('expire' => 3600 * 24 * 3650, 'path' => '/'));
            }
            Session::$user["userName"] = $userName;
        }
    }

    //手机端授权
    public function oauthPhone($by=null)
    {
        $customerId = Session::$user['customerId'];
        $force = $_GET["force"]; //订单页面需要强制授权
        $srcUrl = $_GET['srcUrl'];

        //微信浏览器授权
        $userName = cookie("openid_$customerId");
        if (isMicroMessengerUserAgent()) {
            $clear = $_GET["clear"];
            if ($clear || strpos($userName, "gid_") !== false) {
                cookie("openid_$customerId", null);
                cookie("unionID_$customerId", null);
                cookie("userId_$customerId", null);
                $userName = '';
            }
            $UnionID = cookie("unionID_$customerId");
            $scope = $_GET["scope"];
            if ($scope) {
                if(!empty($userName)){
                    $userModel = D("user");
                    $userWhere['userName']=array('eq',$userName);
                    $newTime = date("Y-m-d H:i:s");
                    $userWhere['subscribeTime'] =array('gt',date('Y-m-d H:i:s',strtotime("$newTime - $scope day")));
                    $result = $userModel->where($userWhere)->find();
                    $result?$force=0:$force=1;
                }
                $scope = SNSAPI_USERINFO;
            } else {
                $scope = SNSAPI_BASE;
            }
//          if(empty($userName)){
//              $userName=$_GET["userName"];
//              Log::write('地址栏userName is '. $userName);
//          }

            if ($force || empty($userName)) { //  需要强制授权或者cookie中userName为空
                $access = WeixinApi::getOauthAccessToken($scope,$srcUrl);//授权
                 log::write("menghuidayiin在oauthPhone中.access".json_encode($access));
                if ($access) {
                    Session::$user['userName'] = $access->openid;
                    Session::$user['unionID'] = $access->unionid;
                    $userName = Session::$user['userName'];
                    $UnionID = Session::$user['unionID'];
                    $this->setOauthCookie($userName, $UnionID);
                    if ($access) { //高级授权获取用户信息入库
                        if ($scope == SNSAPI_USERINFO) {
                            $userInfo = WeixinApi::getOauthUserInfo($access);
                            if ($userInfo) {
                                $userId = $this->setUserOauthToken($userName, $access->access_token, $access->expiration, $access->refresh_token, $UnionID);
                                log::write("menghuidayiin在oauthPhone中.userId".$userId);
                                $this->addUserInfoToDb($userName, $UnionID, $userInfo, $userId);

                            }
                        } else { //普通授权
                            $userInfo = WeixinApi::getUserInfo($userName);
                            if ($userInfo) {
                                $userId = $this->setUserOauthToken($userName, $access->access_token, $access->expiration, $access->refresh_token, $UnionID, USER_STATUS_SUBSCRIBE, $userInfo->subscribe_time, $userInfo->tagid_list);
                                $this->addUserInfoToDb($userName, $userInfo->unionid, $userInfo, $userId);
                            } else {
                                $userId = $this->setUserOauthToken($userName, $access->access_token, $access->expiration, $access->refresh_token, $UnionID);
                                $this->addUserInfoToDb($userName, $UnionID, "", $userId);
                            }
                        }
                    }
                } else {
                    Log::write('授权出错');
                    Session::$user['userName'] = "";
                    Session::$user['unionID'] = "";
                    $return['code'] = 2;
                    $return['msg'] = "授权出错";
                    Output::instance()->object($return);
                    return;
                }
            }
            if (!Session::$user["userId"]) {
                $userId = cookie("userId_$customerId");
                if (!$userId) {
                    $userModel = D("user");
                    $userId = $userModel->where("openid='$userName'")->getField("id");
                    Session::$user["userId"] = $userId;
                } else {
                    Session::$user["userId"] = $userId;
                }
            }
            if (!empty($userName)) {
                Session::$user["userName"] = $userName;
            }
            if (!empty($UnionID)) {
                Session::$user["unionID"] = $UnionID;
            }
            $userName = Session::$user["userName"];
            $UnionID = Session::$user["unionID"];
            if (empty($userName)) {
                Output::instance()->resultCode(code_access_denied);
                return;
            }else{
                if (empty($by)){
                    $return['code'] = 1;
                    $return['msg'] = "授权成功";
                    Output::instance()->object($return);
                    return;
                }

            }
        } else {
            if (!$userName) {
                $Guid = new Guid();
                $userName = $Guid->toString();//生成临时userName;
                $userName = "gid_" . str_replace('-', "", substr($userName, 0, 28));
                cookie("openid_$customerId", $userName, array('expire' => 3600 * 24 * 3650, 'path' => '/'));
            }
            Session::$user["userName"] = $userName;
        }
    }
    private function addUserInfoToDb($openid, $UnionID, $result, $userId)
    {
        if (empty($openid)) {
            return;
        }
        $customerId = Session::$user["customerId"];
        Session::switchCustomer(0);
        $quanUser = M("quan_user");
        Session::switchCustomer($customerId);
        $UserWeixinInfoModel = D('user_weixin_info');
        if (!$UnionID && $result->unionid) {
            Session::$user['unionID'] = $result->unionid;
            $this->setOauthCookie($openid, $UnionID);
            $UnionID = $result->unionid;
        }
        if ($userId) {
            $whereUserInfo['userId'] = $userId;
            $userInfo = $UserWeixinInfoModel->where($whereUserInfo)->find();
        } else if ($UnionID) {
            $whereUserInfo['unionid'] = $UnionID;
            $userInfo = $UserWeixinInfoModel->where($whereUserInfo)->find();
            if (!$userInfo) {
                $whereUserInfo = null;
                $whereUserInfo['openid'] = $openid;
                $userInfo = $UserWeixinInfoModel->where($whereUserInfo)->find();
            }
        } else {
            $whereUserInfo['openid'] = $openid;
            $userInfo = $UserWeixinInfoModel->where($whereUserInfo)->find();
        }
        if ($userInfo) {
            if ($result) {
                $UserWeixinInfoModel->openid = $openid;
                $UserWeixinInfoModel->nickname = json_decode(json_encode($result->nickname));
                $UserWeixinInfoModel->sex = $result->sex;
                $UserWeixinInfoModel->userId = $userId;
                $UserWeixinInfoModel->language = $result->language;
                $UserWeixinInfoModel->city = $result->city;
                $UserWeixinInfoModel->province = $result->province;
                $UserWeixinInfoModel->country = $result->country;
                $UserWeixinInfoModel->headimgurl = $result->headimgurl;
                $UserWeixinInfoModel->subscribe = $result->subscribe;
                $UserWeixinInfoModel->unionid = $UnionID;
                $UserWeixinInfoModel->where($whereUserInfo)->save();
            }
        } else {
            $UserWeixinInfoModel->create();
            $UserWeixinInfoModel->openid = $openid;
            if ($result) {
                $UserWeixinInfoModel->nickname = json_decode(json_encode($result->nickname));
                $UserWeixinInfoModel->sex = $result->sex;
                $UserWeixinInfoModel->language = $result->language;
                $UserWeixinInfoModel->city = $result->city;
                $UserWeixinInfoModel->province = $result->province;
                $UserWeixinInfoModel->country = $result->country;
                $UserWeixinInfoModel->subscribe = $result->subscribe;
                $UserWeixinInfoModel->headimgurl = $result->headimgurl;
                $UserWeixinInfoModel->unionid = $UnionID;
            }
            $UserWeixinInfoModel->userId = $userId;
            $UserWeixinInfoModel->add();
        }
        if($userId&&$customerId){
            $sql = "update wx_quan_user a inner join wx_miyouquan b on a.qid=b.id set a.nickName = '". $result->nickname."',a.headImgUrl='".$result->headimgurl."' where b.cId=$customerId and a.uid=$userId";
            M("")->query($sql);
        }
    }

    private static function setUserOauthToken($fromUserName, $token, $expiration, $refreshToken, $UnionID, $SUBSCRIBE = USER_STATUS_SHARE_SUBSCRIBE, $subscribe_time = null, $tagid_list = null)
    {
        $customerId = Session::$user['customerId'];
        $User = D("user");
        $userWeixin = D("user_weixin_info");
        if ($UnionID) {
            $mp['unionid'] = $UnionID;
        } else {
            $mp['openid'] = $fromUserName;
        }
        $userId = $userWeixin->where($mp)->getField("userId");
        $data['openid'] = $fromUserName;
        $data['oauthAccessToken'] = $token;
        $data['oauthAccessExpiration'] = $expiration;
        $data['oauthRefreshToken'] = $refreshToken;
        $subscribe_time ? $data['subscribeTime'] = $subscribe_time: "";
        if ($tagid_list) {
            foreach ($tagid_list as $key => $value) {
                $tag[$key] = $value;
            }
            $tag = implode(",", $tag);
            $data['groupId'] = $tag;
        }
        if (!$userId) {
            $userId = $User->where("openid='$fromUserName'")->getField("id");
        }
        if ($userId) {
            //获取当前用户状态
            $userStatus = $User->where("openid='$fromUserName'")->getField("status");
            //更新的状态为subscribe(关注) 并且 当前用户的状态不为 scansubscribe(扫码关注)和 subscribe(关注)的条件下进行更新
            if($SUBSCRIBE == USER_STATUS_SUBSCRIBE && $userStatus != USER_STATUS_SUBSCRIBE && $userStatus != USER_STATUS_SCAN_SUBSCRIBE){
                $data['status'] = $SUBSCRIBE;
            }
            $User->where("id=$userId")->save($data);
            $id = $userId;
        } else {
            $data['lastTime'] = date("Y-m-d H:i:s");
            $data['status'] = $SUBSCRIBE;
            $data['userName'] = $fromUserName;
            $data['profileUrl'] = DEFAULT_PROFILE_URL;
            $data['isNew'] = 1;
            $id = $User->add($data);
            $pointData = ['uId' => $id];
            self::newUserPoint($pointData);
            $token = self::createToken($id);
            $User->where(['id' => $id])->save(['token' => $token, 'expired' => date("Y-m-d",strtotime("+1 month"))]);
        }
        //Log::write('jie----111'.$User->getLastSql());
        return $id;
    }

    //创建token
    public function createToken($userId){
        $ychar = "0,1,2,3,4,5,6,7,8,9";
        $list = explode(",", $ychar);
        $code = '';
        for ($i = 0; $i < 14; $i++) {
            $randnum = rand(0, 9);
            $code .= $list[$randnum];
        }
        $code .=$userId;
        return $code;
    }

    private function callModuleWithUserInfo($userInfo, $module)
    {
        $params = new stdClass();
        $params->nickname = $userInfo->nickname;
        $params->sex = $userInfo->sex;
        $params->province = $userInfo->province;
        $params->city = $userInfo->city;
        $params->country = $userInfo->country;
        $params->headimgurl = $userInfo->headimgurl;
        $params->perr = false;
        Module::callModule($module, Session::$user, 'setuserinfo', $params);
    }

    private function verifyAccessTags($accesstagids)
    {
        $customerId = Session::$user['customerId'];
        $fromUserName = Session::$user['userName'];
        $Accesstag = M("user_access_tag");
        $mc["accesstagid"] = array('in', $accesstagids);
        $mc["fromUserName"] = array('eq', $fromUserName);
        $accessArr = $Accesstag->where($mc)->find();
        if ($accessArr) {
            return 1;
        } else {
            return 0;
        }

    }

    /**
     * 构造http请求
     * @param $url
     * @return mixed
     */
    private static function httpGet($code, $appid, $secret)
    {
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $appid . '&secret=' . $secret . '&js_code=' . $code . '&grant_type=authorization_code';
        $curl = curl_init();//初始化一个 cURL 对象
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);// 获取数据返回
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);//设置一个长整形数，作为最大延续多少秒
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_BINARYTRANSFER, true); // 在启用 CURLOPT_RETURNTRANSFER 时候将获取数据返回
        $res = curl_exec($curl);
        curl_close($curl);
        return json_decode($res, true);
    }

    private function addUserInfoToDbApp($result, $userId = '')
    {
        if (empty($result)) {
            return;
        }
        $customerId = Session::$user['customerId'];
        $UserWeixinInfoModel = D('user_weixin_info');
        if ($userId) {
            $whereUserInfo['userId'] = $userId;
        } else if ($result->unionId) {
            $whereUserInfo['unionid'] = $result->unionId;
        } else {
            $whereUserInfo['openid'] = $result->openId;
        }
        $userInfo = $UserWeixinInfoModel->where($whereUserInfo)->find();
        if ($userInfo) {
            if ($result) {
                $UserWeixinInfoModel->nickname = json_decode(json_encode($result->nickname));
                $UserWeixinInfoModel->sex = $result->gender;
                $UserWeixinInfoModel->language = $result->language;
                $UserWeixinInfoModel->city = $result->city;
                $UserWeixinInfoModel->province = $result->province;
                $UserWeixinInfoModel->country = $result->country;
                $UserWeixinInfoModel->headimgurl = $result->avatarUrl;
                $UserWeixinInfoModel->userId = $userId;
                $UserWeixinInfoModel->where($whereUserInfo)->save();
            }
        } else {
            $UserWeixinInfoModel->create();
            $UserWeixinInfoModel->openid = $result->openId;
            if ($result) {
                $UserWeixinInfoModel->nickname = json_decode(json_encode($result->nickname));
                $UserWeixinInfoModel->sex = $result->gender;
                $UserWeixinInfoModel->language = $result->language;
                $UserWeixinInfoModel->city = $result->city;
                $UserWeixinInfoModel->province = $result->province;
                $UserWeixinInfoModel->country = $result->country;
                $UserWeixinInfoModel->headimgurl = $result->avatarUrl;
                $UserWeixinInfoModel->unionid = $result->unionId;
                $UserWeixinInfoModel->userId = $userId;
                $UserWeixinInfoModel->subscribe_time = date('Y-m-d H:i:s', time());
            }
            $result = $UserWeixinInfoModel->add();
        }
    }
    public function checkCustomer($customerId){
        Session::switchCustomer(0);
        $customer_user = M('customer_user');
        Session::switchCustomer($customerId);
        $status = $customer_user->where(['customerId' => $customerId,'agent' => 'business'])->getField('status');

        if($status == 'close'){
            Output::instance()->resultCode(1,"噢噢，该账号暂时无法访问，欲知后事如何，请紧密关注！！");
            return;
        }
    }
    public function scanVisit($obj){
        $customerId = Session::$user['customerId'];
        $uid = $obj->uid;
        $scanId = $obj->scanId;
        $isDefault = $obj->isDefault;
        $sId = $obj->sId;
        Session::switchCustomer(0);
        $LogModel = M("qrcode_scan_log");
        $mimallModel = M("mimall_user");
        $quanProductModel = M("module_quanuser_product");
        $posterModel = M("poster");
        $QRModel = M("qrcode");
        Session::switchCustomer($customerId);
        $user = M('user');
        $userName= $user->where(['id' => $uid])->getField('userName');
        if($isDefault == 1){
            $quanProductModel->where("id=$scanId")->setInc('pv');
            $data["defaultId"] = $scanId;
            $data["fromCustomerId"] = $customerId;
            $data["fromUserName"] = $userName;
            $data["createTime"] = date("Y-m-d H:i:s");
            $LogModel->add($data);
        }elseif ($isDefault == 2){
            $where["sceneId"] = $scanId;
            $where["fromCustomerId"] = $customerId;
            $posterId = $QRModel->alias('a')->join("wx_module_user_poster as b on b.id = a.moduleId")->where($where)->getField('moduleId');
            $posterModel->where(['id' => $posterId])->setInc('pv');
            $params=new StdClass();
            $params->uid = $uid;
            $params->userName = $userName;
            $params->scanId = $scanId;
            $params->cid = $customerId;
            Module::callModule('qrcode', Session::$user, 'QrUrl', $params);
        }
        $mimallUser = $mimallModel->where(['cId' => $customerId, 'uId' => $uid])->find();
        $obj->sId = $sId;
        $obj->miUId = $mimallUser['miUid'];
        $obj->qId = $mimallUser['qId'];
        $obj->saleSourceUid = $mimallUser['saleSource'];
        return $obj;

    }
}